1

题目要求:
给定一个有序(非降序)数组A,可含有重复元素。找到大于target(目标值)的最小元素位置,目标不存在则返回-1

不考虑算法复杂度实现:

nums = list(map(int,input().split()))
target = int(input())
def searchRange(nums,target):
    n = len(nums)
    for i in range(len(num)):
        if nums[i]>target:
            return i 
        else:
            return -1
            
print(searchRange(nums,target))

优化(二分查找)

nums = list(map(int,input().split()))
target = int(input())
def searchRange(nums,target):
    n = len(nums)
    if n>=1:
        v = n//2
        if nums[v] == target :
            return v
        elif target<nums[v]:
            return searchRange(nums[:v],target)
        elif target>nums[v]:
            return searchRange(nums[v+1:],target)
    return -1

print(searchRange(nums,target))

二分查找最优时间复杂度O(1),最坏时间复杂度O(N)


SheenStar
168 声望26 粉丝

祝你坚强